﻿using System;
using System.IO;
using System.Threading.Tasks;

namespace BaseSyntax.ThreadTest
{
	public class TaskErrorCatcher:ITest
	{
		void CatchMulTask()
		{
			Task task = Task.Run(()=>{
				Console.WriteLine("create error");
				throw new ArgumentException();
			});

			Task task1 = task.ContinueWith(newTask =>
			{
				Console.WriteLine("create error 1");
				throw  new FileLoadException();
			});
			try
			{
				Task.WaitAll(task, task1);
			}	
			catch (AggregateException e)
			{
				Console.WriteLine($"ErrorRRRRRRRRRRRR: {e}");
				// throw;
			}
		}
		
		public void Test()
		{
			bool parentTaskFaulted = false;
			Task task = new Task(() =>
			{
				throw new InvalidOperationException();
			});
			Task continuationTask = task.ContinueWith(
				(antecedentTask) =>
				{
					parentTaskFaulted =
						antecedentTask.IsFaulted;
				}, TaskContinuationOptions.OnlyOnFaulted);
			task.Start();
			continuationTask.Wait();
			
			if (!parentTaskFaulted)
			{
				throw new Exception("Parent task should be faulted");
			}
			
			if (!task.IsFaulted)
			{
				throw new Exception("Task should be faulted");
			}
			
			task.Exception.Handle(eachException =>
			{
				Console.WriteLine(
					$"ERROR: { eachException.Message }");
				return true;
			});
		}
	}
}